
import cv2
import numpy as np
import time
import matplotlib.pyplot as plt
import scipy
import os

pts = np.array([[5, 5], [20, 30], [70, 25], [50, 20], [10, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))

font = cv2.FONT_HERSHEY_SIMPLEX

print("Used Optimized ", cv2.useOptimized())

# flags = []
#
# for i in dir(cv2):
#     if i.startswith("COLOR_"):
#         flags.append(i)
#         print(i)
#
# print(flags)


green = np.uint8([[[0, 255, 0]]])
hsv_green = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
print(hsv_green)

# 图像文件路径
imgFilePath = 'D:/Data/WoKe/2021-03-12/GuideData/GuideData/'
# 得到指定路径下的所有文件
imgFileList = os.listdir(imgFilePath)

# 循环遍历图像文件呢
for imgName in imgFileList:
    # 判断后缀为bmp格式
    if imgName.endswith(".bmp"):
        # print("图像名字: ", imgName)
        # 读取图像
        img = cv2.imread(imgFilePath+imgName, cv2.IMREAD_COLOR)
        print("图像路径名: ", imgFilePath+imgName,)
        # img = cv2.imread("D:/Data/WoKe/2021-03-12/GuideData/GuideData/134.bmp", cv2.IMREAD_COLOR)
        img2 = cv2.imread('D:/pythonProject/Lena.bmp', cv2.IMREAD_GRAYSCALE)

        # 转换为灰度图像
        imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # 打印图像尺寸信息
        # rows, cols, channels = img.shape
        #
        # print("rows : %d, cols : %d, channels : %d" % img.shape)
        #
        # print(len(img.shape))

        # 图像二值化
        ret, binImg = cv2.threshold(imgGray, 170, 255, cv2.THRESH_BINARY)

        # 检测二值图像的轮廓
        contours, hierarchy = cv2.findContours(binImg, cv2.RETR_CCOMP, 1)

        # 画出轮廓
        drawImg = cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

        # 打印检测出的轮廓数量
        print("轮廓数量: ", len(contours))

        maxContourID = 0
        maxVal = 0
        # 遍历所有轮廓，找到最大轮廓Id
        for i in range(len(contours)):

            if len(contours[i]) > maxVal:

                maxVal = len(contours[i])
                maxContourID = i

        # 得到最大轮廓
        maxContour = contours[maxContourID]

        # 查找凸包
        hull = cv2.convexHull(maxContour, returnPoints=False)

        # 凸缺陷检测
        defects = cv2.convexityDefects(maxContour, hull)

        for i in range(defects.shape[0]):
            s, e, f, d = defects[i, 0]
            start = tuple(maxContour[s][0])
            end = tuple(maxContour[e][0])
            far = tuple(maxContour[f][0])
            # print(i, "距离:", d)
            cv2.line(img, start, end, [0, 255, 0], 2)
            cv2.circle(img, far, 5, [0, 0, 255], -1)

        # cv2.ellipse(img, (200, 200), (100, 50), 0, 0, 180, (255, 0, 0), -1)
        # cv2.polylines(img, [pts], True, (0, 0, 255), 2)
        # cv2.putText(img, "OpenCV", (100, 300), font, 2, (0, 255, 255), 2)

        # e1 = cv2.getTickCount()
        # for i in range(5, 49, 2):
        #     img1 = cv2.medianBlur(img, i)
        # e2 = cv2.getTickCount()
        # t = (e2 - e1) / cv2.getTickFrequency()

        # print("总耗时 : %f (s)" % t)

        cv2.imshow("drawImg", drawImg)
        cv2.imshow('image', img)
        cv2.waitKey(0)

cv2.destroyAllWindows()

# 两种显示图像的方法；
#  第一种方法就是每个功能单独一句话

# plt.subplot(1, 2, 1)
# plt.imshow(img)
# plt.title('img')
# plt.subplot(1, 2, 2)
# plt.imshow(img)
# plt.imshow(img2)
# plt.title('img2')
# plt.show()

#  第二种方法就是使用逗号将几个功能句在一行中
# plt.subplot(121), plt.imshow(img, 'gray'), plt.title('img')
# plt.axis('off')
# plt.subplot(122), plt.imshow(img2, 'gray'), plt.title('img2')
# plt.axis('off')
# plt.xticks(range(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
# plt.show()

# t=np.arange(0.0,2.0,0.1)
# s=np.sin(t*np.pi)
# plt.subplot(2,2,1) #要生成两行两列，这是第一个图plt.subplot('行','列','编号')
# plt.plot(t,s,'b--')
# plt.ylabel('y1')
# plt.subplot(2,2,2) #两行两列,这是第二个图
# plt.plot(2*t,s,'r--')
# plt.ylabel('y2')
# plt.subplot(2,2,3)#两行两列,这是第三个图
# plt.plot(3*t,s,'m--')
# plt.subplot(2,2,4)#两行两列,这是第四个图
# plt.plot(4*t,s,'k--')
# plt.show()